package cn.dansj.common.utils.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;

import java.io.IOException;

class JSONNodeDeserializer extends JsonNodeDeserializer {
    public static final JsonNodeDeserializer INSTANCE = new JSONNodeDeserializer();

    @Override
    public JsonNode deserialize(JsonParser p, DeserializationContext context) throws IOException {
        JsonNode node = super.deserialize(p, context);
        return context.isEnabled(NumericFeature.USE_STRING_FOR_NUMERIC) ? convertNumbersToStrings(node) : node;
    }

    private JsonNode convertNumbersToStrings(JsonNode node) {
        if (node.isNumber()) {
            return new TextNode(node.asText()); // 数字转字符串
        } else if (node.isArray()) {
            ArrayNode arrayNode = (ArrayNode) node;
            ArrayNode newArray = arrayNode.arrayNode();
            for (JsonNode child : arrayNode) {
                newArray.add(convertNumbersToStrings(child));
            }
            return newArray;
        } else if (node.isObject()) {
            ObjectNode objectNode = (ObjectNode) node;
            ObjectNode newObject = objectNode.objectNode();
            node.fields().forEachRemaining(entry -> {
                newObject.set(entry.getKey(), convertNumbersToStrings(entry.getValue()));
            });
            return newObject;
        }
        return node;
    }
}
